package com.teetaa.util;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;

import javax.imageio.ImageIO;

public class ImageHepler {
	private static BufferedImage makeThumbnail(Image img, int width, int height) {
		BufferedImage tag = new BufferedImage(width, height, 1);
		Graphics g = tag.getGraphics();
		g.drawImage(img.getScaledInstance(width, height, 4), 0, 0, null);
		g.dispose();
		return tag;
	}

	/** */
	/**
	 * 旋转图片为指定角度
	 * 
	 * @param bufferedimage
	 *            目标图像
	 * @param degree
	 *            旋转角度
	 * @param outImageFile
	 *            输出为文件，为空则不操作
	 * @return
	 */
	public static BufferedImage rotateImage(final BufferedImage bufferedimage,
			final int degree, File outImageFile) throws IOException {
        int w = bufferedimage.getWidth();
        int h = bufferedimage.getHeight();
        int type = bufferedimage.getColorModel().getTransparency();
        BufferedImage img;
        Graphics2D graphics2d;
        int longside = Math.max(w, h);
        (graphics2d = (img = new BufferedImage(longside,longside, type))
                .createGraphics()).setRenderingHint(
                RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        
        int offe = Math.max(w, h) - Math.min(w, h);
        
        graphics2d.translate(w<h?offe/2:0, w>h?offe/2:0);
        graphics2d.rotate(Math.toRadians(degree), w / 2, (h / 2));
        graphics2d.drawImage(bufferedimage, 0, 0, null);
        graphics2d.dispose();

		if (null != outImageFile)
			saveImage(img, outImageFile, true);
		return img;
	}

	/** */
	/**
	 * 把图片按指定类型另存
	 * 
	 * @param ext
	 *            目标扩展名
	 * @param sourseimagefile
	 *            源图像文件
	 * @param desimagefile
	 *            目标图像文件
	 * @return
	 */
	public static boolean saveAsImageFile(File sourseimagefile, File desimagefile,
			boolean overwrite) throws IOException {
		BufferedImage image = ImageIO.read(sourseimagefile);
		return saveImage(image, desimagefile, overwrite);
	}

	public static boolean saveImage(BufferedImage image, File outImageFile,
			boolean overwrite) throws IOException {
		String fileName = outImageFile.getName();
		if (outImageFile.exists())
			if(!overwrite)
				return false;
			else 
				outImageFile.delete();

		String formatName = fileName.substring(fileName.lastIndexOf(46) + 1);
		return ImageIO.write(image, formatName, outImageFile);
	}

	/**
	 * 删除指定目录下全部文件,可自动删除子目录下文件
	 * @param dir	指定目录
	 * @throws IOException
	 */
	public static void delAllFile( File dir) throws IOException{
		LinkedList<File> list = new LinkedList<File>();  
        File file[] = dir.listFiles(); 
        for (int i = 0; i < file.length; i++) { 
            if (file[i].isDirectory()) 
                list.add(file[i]); 
            else 
                file[i].delete(); 
        } 

	}
	
	public static void saveSubImage(BufferedImage image,
			Rectangle subImageBounds, File subImageFile) throws IOException {
		String fileName = subImageFile.getName();
		String formatName = fileName.substring(fileName.lastIndexOf(46) + 1);
		BufferedImage subImage = new BufferedImage(subImageBounds.width,
				subImageBounds.height, 1);
		Graphics g = subImage.getGraphics();
		if ((subImageBounds.width > image.getWidth())
				|| (subImageBounds.height > image.getHeight())) {
			int left = subImageBounds.x;
			int top = subImageBounds.y;
			if (image.getWidth() < subImageBounds.width)
				left = (subImageBounds.width - image.getWidth()) / 2;
			if (image.getHeight() < subImageBounds.height)
				top = (subImageBounds.height - image.getHeight()) / 2;
			g.setColor(Color.white);
			g.fillRect(0, 0, subImageBounds.width, subImageBounds.height);
			g.drawImage(image, left, top, null);
			ImageIO.write(image, formatName, subImageFile);
			System.out.println("if is running left:" + left + " top: " + top);
		} else {
			g.drawImage(image.getSubimage(subImageBounds.x, subImageBounds.y,
					subImageBounds.width, subImageBounds.height), 0, 0, null);
			System.out.println("else is running");
		}
		g.dispose();
		ImageIO.write(subImage, formatName, subImageFile);
	}

	public static void cut(String srcImageFile, String descDir, int width,
			int height, Rectangle rect) throws IOException {
		Image image = ImageIO.read(new File(srcImageFile));
		BufferedImage bImage = makeThumbnail(image, width, height);

		saveSubImage(bImage, rect, new File(descDir));
	}

	public static void cut(File srcImageFile, File descDir, int width,
			int height, Rectangle rect) throws IOException {
		Image image = ImageIO.read(srcImageFile);
		BufferedImage bImage = makeThumbnail(image, width, height);

		saveSubImage(bImage, rect, descDir);
	}
}